package com.nio.c1_NettyTest;

//ByteBffer 与String  相互转换

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;

public class ByteBufferStringTest {
    public static void main(String[] args) {
        //1.  字符串转换为ByteBuffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(16);
        ByteBuffer put = byteBuffer.put("herman".getBytes());
        //基本方式，写完读取的话=需要用flip切换到读模式
        byteBuffer.flip();
        while (byteBuffer.hasRemaining()){
            byte b = byteBuffer.get();
            System.out.print((char)b);
        }

        System.out.println("======--.getBytes()转换为字符串");
        //2.Charset   写完自动切换到读模式
        ByteBuffer herman = StandardCharsets.UTF_8.encode("herman");

        while(byteBuffer.hasRemaining()){
            byte b = byteBuffer.get();
            System.out.print((char)b);
        }
        System.out.println("========StandardCharset转化为字符串");


        //3.wrap     包围缠绕            写完自动切换到读模式
        ByteBuffer wrap = ByteBuffer.wrap("herman".getBytes());

        while(byteBuffer.hasRemaining()){
            byte b = byteBuffer.get();
            System.out.print((char)b);
        }
        System.out.println("=======ByteBuffer.wrap(--.getBytes())方法");

        //byteBuffer 转换为String


        CharBuffer decode = StandardCharsets.UTF_8.decode(herman);
        System.out.println(decode.toString()+"===StandardCharsets.UTF_8.decode()方法将byteBuffer转换为字符串");


        put.flip();   //基本方法转换为字符串时  需要先转换为读模式
        String string = StandardCharsets.UTF_8.decode(put).toString();
        System.out.println(string+"===用byteBuffer.put(--.getBytes())放进去的转换为字符串");
    }
}
